package com.xlh.dokka.svc.core.model;

import com.xlh.util.SshUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import static org.apache.commons.lang3.StringUtils.*;

/**
 * @author cheer
 */
@Slf4j
@Data
public class ResourceUsage {

    private Integer totalCpus;

    private Double cpuUsage;

    private Long totalMemory;

    private Long usedMemory;

    private Long totalDisk;

    private Long usedDisk;

    private static final String QUERY_CPU_COUNT = "cat /proc/cpuinfo| grep \"processor\"| wc -l";

    private static final String QUERY_CPU_USAGE = "top -bn 1 -i -c";

    private static final String QUERY_MEMORY = "free";

    private static final String QUERY_DISK = "df";

    public Boolean sync(SshUtil sshUtil) {
        try {
            // 查询cpu核心数量
            String cpuCount = sshUtil.exec(QUERY_CPU_COUNT).replaceAll(LF, EMPTY);
            this.totalCpus = Integer.valueOf(cpuCount);

            // 查询cpu使用率
            String cpuUsage = sshUtil.exec(QUERY_CPU_USAGE).split(LF)[2].replaceAll(" +", SPACE); // 多个空格转成1个空格
            try {
                this.cpuUsage = (1000 - Double.valueOf(cpuUsage.split(SPACE)[7]) * 10) / 1000; // 用1000去减防止浮点数减法产生多位小数
            } catch (NumberFormatException ignored) {
                this.cpuUsage = 0d;
            }

            // 查询内存总量与使用量
            String memory = sshUtil.exec(QUERY_MEMORY).split(LF)[1].replaceAll(" +", SPACE); // 多个空格转成1个空格
            this.totalMemory = Long.valueOf(memory.split(SPACE)[1]);
            this.usedMemory = Long.valueOf(memory.split(SPACE)[2]);

            // 查询挂载根目录"/"的磁盘总量与使用量
            String diskResult = sshUtil.exec(QUERY_DISK);
            String[] diskArray = diskResult.split(LF);
            for (String disk : diskArray) {
                if (disk.endsWith("/")) {
                    disk = disk.replaceAll(" +", SPACE); // 多个空格转成1个空格
                    this.totalDisk = Long.valueOf(disk.split(SPACE)[1]);
                    this.usedDisk = Long.valueOf(disk.split(SPACE)[2]);
                }
            }

            return true;
        } catch (Exception e) {
            log.warn("resource usage sync failed：{}", e.getMessage(), e);
            return false;
        }
    }
}
